var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
var excelType=0;
$(function () {

    $('#pp').removeAttr('onclick');//去掉a标签中的onclick事件
    $("#pp").css({'background': '#999', 'borderColor': '#999', 'color': '#fff'});
});

function searchList(excel) {
    $.ajax({
        url: root.cooperation.conditionQuery,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "total":"",
            "totalPage":"",
            "pageNumber":1,
            "pageSize":9,
            "startIndex":"",
            "store":{
                "type":$('#type').val(),
                "company_name":$('#company_name').val(),
                "state":$('#state').val(),
                "receiver_province_name":$('#receiver_province_name').val(),
                "excel":excel,
                "PageSize":"",
                "Startindex":""
            }

        }),
        success: function (data) {
            $('#pp'). attr('onclick',"checkSubmit(1);");
            $('#pp').removeAttr('style');
            console.log(data);
            sessionStorage.setItem("cooperstate1",'')
            sessionStorage.setItem("cooperstate2",'')
            sessionStorage.setItem("coopertype",'')
            // couponlist(data.result);
            couponlist(data.list, 0);
            $('.M-box3').pagination({
                pageCount: data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    console.log(api)
                    $.ajax({
                        url: root.cooperation.conditionQuery,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "total":"",
                            "totalPage":"",
                            "pageNumber":api.getCurrent(),//获取当前页码
                            "pageSize":9,
                            "startIndex":"",
                            "store":{
                                "type":$('#type').val(),
                                "company_name":$('#company_name').val(),
                                "state":$('#state').val(),
                                "receiver_province_name":$('#receiver_province_name').val(),
                                "excel":excel,
                                "PageSize":"",
                                "Startindex":""
                            }
                        }),
                        success: function (result) {
                            console.log(result)
                            couponlist(result.list);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

// var j = 0;
function couponlist(data, index){
    // var j = 0;
    dataSource.splice(0,dataSource.length);//清空数组
    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.type);
        rowData.push(field.company_name);
        rowData.push(field.receiver_province_name);
        rowData.push(field.linkman);
        rowData.push(field.linkman_post);
        rowData.push(field.linkman_phone);
        rowData.push(field.create_time);
        rowData.push(field.state);
        rowData.push(field.handle_man);
        rowData.push(field.handle_results);
        rowData.push(field.handle_time);
        rowData.push(field.id);
        dataSource.push(rowData);
    });

    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[2]=='请选择收货区域'){
                            val=''
                        }else {
                            val=row[2]
                        }
                        return val;

                    },
                    "targets":2
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[7]==10){
                            val='待处理'
                            row[10]=''
                        }
                        else if(row[7]==20){
                            val='处理中'
                        }
                        else if(row[7]==30){
                            val='已处理'
                        }
                        return val;
                    },
                    "targets":7
                },
                {
                    "render": function (data, type, row, meta) {
                        console.log(row[0])
                        var val = '';
                        if (row[0] == 2) {
                            val='供应商合作'
                        } else if (row[0] == 3) {
                            val='采购商合作'
                        }else if (row[0] == 4) {
                            val='AIC合作'
                        }
                        return val;
                    },
                    "targets":0
                },
                {
                    "render": function (data, type, row, meta) {
                        // console.log(dataSource[index++]);
                        // console.log(dataSource[index++][11]);
                        var val='';
                        if(row[7]==10){
                            val = '<div class="action" id="action'+row[11]+'"><a class="powerButton 215" style="margin-right: 20px"><span class="list" id="'+row[11]+'" onclick="confirm('+row[11]+')">处理</span></a>';

                            if (row[0] == 2){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("供应商")
                            } else if (row[0] == 3){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use2.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("采购商")
                            }else if (row[0] == 4){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-AIC.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("AIC合作")
                            }

                        }
                        else if(row[7]==20){
                            val='<div class="action" id="action'+row[11]+'"><a class="powerButton 215" style="margin-right: 20px"><span class="list" id="'+row[11]+'" onclick="confirm('+row[11]+')">处理</span></a>';

                            if (row[0] == 2){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("供应商")
                            } else if (row[0] == 3){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use2.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("采购商")
                            }else if (row[0] == 4){
                                val+='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-AIC.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("AIC合作")
                            }

                        }
                        else if(row[7]==30){
                            if (row[0] == 2){
                                val='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("供应商")
                            } else if (row[0] == 3){
                                val='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-use2.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("采购商")
                            }else if (row[0] == 4){
                                val='<a class="powerButton 213"><span class="list"  onclick="detail(\'合作申请\',\'cooperation-AIC.html\',\''+row[11]+'\')">查看</span></a></div>' ;
                                console.log("AIC合作")
                            }
                        }
                        return val;
                    },
                    "targets":11
                }
            ]
        });
//权限控制函数
        power()
    };
}
//弹框
var index=0;
function confirm(id,name) {
    var popEle = $('#chuliPop');
    var curInd = layer.confirm('<textarea id="handle_results" style="width:200px;height:100px;resize: none;" maxlength="200" placeholder="请填写处理结果"></textarea>', {title:'提示',btn: ['保存', '完结']}, function(index){

        var inv = $("#handle_results").val();
        finish1(id,curInd,name)
        layer.close(curInd);
    },function(){
        finish2(id,curInd,name)
        layer.close(curInd);
        var inv = $("#handle_results").val();
        layer.close(curInd);

    });
}
//第一个
function finish1(id,val){
    var target = document.getElementById(''+id+'');

    var handle_info=$('#handle_results').val();
    // var target = t.target;

    console.log(target)
    target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.innerHTML=handle_info;

    console.log(handle_results);
    console.log(target);
    var reason=$('#reason'+id+'').val();
    console.log(target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling)
    if(reason!=''){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url: root.cooperation.update,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "sign_id":id,
                "state":20,
                "handle_man":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                "handle_results":$('#handle_results').val()

            }),
            success: function (data) {
                console.log(data)
                /*target.style.color='#999';*/
                target.onclick = null;
                target.setAttribute("onclick", 'confirm('+id+')')

                target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML='处理中'
                searchList(0)
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })}
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}
//第二个
function finish2(id,val){
    var target = document.getElementById(''+id+'');

    var handle_info=$('#handle_results').val();

    target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.innerHTML=handle_info;

    console.log(target);
    var reason=$('#reason'+id+'').val();
    console.log(target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling)
    if(reason!=''){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url: root.cooperation.update,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            // contentType: "application/json",
            data: JSON.stringify({
                "state":30,
                "sign_id":id,
                "handle_man":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                "handle_results":$('#handle_results').val()

            }),
            success: function (data) {
                console.log(data)
                target.style.color='#999';
                target.onclick = null;
                target.parentElement.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML='已处理'
                searchList(0)
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })}
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}
//查看详情
function detail(title,url,sign_id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url +'?sign_id='+sign_id
    });
    layer.full(index);
}


//弹框跳转

var cooperstate1= sessionStorage.getItem("cooperstate1")//待处理
var cooperstate2= sessionStorage.getItem("cooperstate2")//待处理
if (sessionStorage.getItem("coopertype")==4) {
    $('#type').val(sessionStorage.getItem("coopertype"))
    if(cooperstate1==10){
        $('#state').val(cooperstate1)
    }
    searchList(0)
}else {
    if(cooperstate2==20){
        $('#state').val(cooperstate2)
    }
    if(cooperstate1==10){
        $('#state').val(cooperstate1)
    }
    $('#type').val("")
    searchList(0)
}